#ifndef _LUA_SCRIPT_H_
#define _LUA_SCRIPT_H_

extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h "
}

#define SCRIPT_NAME_LEN		(256)

typedef void (*LUA_ERROR_HANDLER)(const char*);

struct LUA_FUNC
{
	const char*		pszFuncName;
	lua_CFunction	pFunc;	
};

class BASELIB_API CLuaScript
{
public:
	CLuaScript();
	~CLuaScript();

	bool Init(void);
	bool UnInit(void);

	bool LoadFromFile(const char* pszFileName);
	bool LoadFromBuffer(const char* pszScriptName, const char* pszBuffer, size_t uSize);

	bool RegisterFunction(LUA_FUNC &rLuaFunc);
	bool RegisterFunctions(LUA_FUNC Funcs[], int nFuncCount = 0);
	static bool RegisterFunctions(lua_State* L, LUA_FUNC Funcs[], int nFuncCount = 0);
	void RegisterErrorHandler(LUA_ERROR_HANDLER pHandler);

	void SafeCallBegin(int* pIndex);
	bool CallFunction(const char* pszFuncName, int nResults, char* pszFormat, ...);
	bool CallFunction(const char* pszFuncName, int nResults, char* pszFormat, va_list vlist);
	bool GetValuesFromStack(char * pszFormat , ...);			
	void SafeCallEnd(int nIndex);

	char* GetScriptName(void);
	bool IsFuncExist(char* pszFuncName);

	bool AddGlobalInteger(const char* pszVarName, int nValue);
	bool AddGlobalString(const char* pszVarName, const char* pszValue);

	lua_State* GetLuaState(void);

private:
	char				m_szScriptName[SCRIPT_NAME_LEN];
	lua_State*			m_LuaState;
	LUA_ERROR_HANDLER	m_pErrorHandler;

	static int _Include(lua_State* L);

	void _EnumTable(lua_State* L, int nTableIndex, int nTableDepth);
	int _LuaErrFunc(lua_State* L);
};

#endif	// _LUA_SCRIPT_H_